package com.yxxmg.enums;

import java.util.Optional;

import org.apache.commons.lang3.StringUtils;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonValue;

/**
 * @author : yxxmg
 * @version : 1.0
 * @description :
 * @since : 2024/12/3
 */
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum Gender {
    MALE(0, "男"), FEMALE(1, "女");

    private final int code;
    @JsonValue // 序列化
    private final String desc;

    Gender(int code, String desc) {
        this.code = code;
        this.desc = desc;
    }

    @JsonCreator(mode = JsonCreator.Mode.DELEGATING) // 反序列化
    public static Gender of(Object object) {
        return Optional.ofNullable(object).map(Gender::map).orElse(null);
    }

    private static Gender map(Object obj) {
        if (obj instanceof Integer) {
            for (Gender gender : Gender.values()) {
                if (gender.code == (Integer)obj) {
                    return gender;
                }
            }
        } else if (obj instanceof String) {
            for (Gender gender : Gender.values()) {
                if (StringUtils.equals(gender.desc, (String)obj)) {
                    return gender;
                }
            }
        }
        return null;
    }
}
